import axios from 'axios'
let htmlparser = require("htmlparser2");
const USERAGENT = `meta-extractor/meta`;
function fixName(name) {
  return name.replace(/(?::|_|-)(\w)/g, (matches, letter) =>
    letter.toUpperCase()
  );
}

function parseMeta(attrs, rx) {
  const name = attrs.name || attrs.property || Object.keys(attrs)[0];
  if (rx.test(name)) {
    return [fixName(name), attrs.content || attrs[name]];
  }
}
function createParser(opts,res){
  const limit = opts.limit;
  const url = new URL(opts.uri);
  res.title = "";
  let isHead = false;
  let current;

  return new htmlparser.Parser({
    onopentag: function(name, attrs){
      current = name;
      if (name === "head") {
        isHead = true;
      }
      if (name === "meta") {
        const meta = parseMeta(attrs, opts.rx);
        if (meta && !res[meta[0]]) {
          res[meta[0]] = meta[1];
        }
      }
    },
    ontext: function(text){
      if (isHead && current === "title") {
        res.title += text;
      }
    },
    onclosetag: function(tagName){
      if (tagName === "head") {
        isHead = false;
      }
    }
  }, {decodeEntities: true});
}
function isBlank(str){
  if (str==null || str=="" || str==undefined || str.trim().length==0){
    return true;
  }
  return false;
}

function _extract(opts,done){
  const uri = opts.uri;
  const limit = opts.limit || 2 * 1024 * 1024;
  opts.headers = Object.assign(
    {
      "User-Agent": USERAGENT,
    },
    opts.headers
  );
  axios.get(uri).then(resp=>{
    let res = {};
    let parser = createParser(opts,res)
    parser.write(resp.data);
    if (isBlank(res.title)){
      res.title = res["ogTitle"] || res["twitterTitle"]
    }
    if (isBlank(res.description)){
      res.description = res["ogDescription"] || res["twitterDescription"]
    }
    if (isBlank(res.imgUrl)){
      res.imgUrl = res["ogImage"] || res["twitterImage"]
    }
    console.log(res)
    done(null,res);
  })
}

export function extractMeta(url,cb){
  let rx = /charset|description|keywords|twitter:|og:|vk:|al:|theme-color/im;
  const opts = {uri:url,rx:rx}
  _extract(opts,cb);
}

